express = require 'express'
path = require 'path'
logger = require 'morgan'
cookieParser = require 'cookie-parser'
bodyParser = require 'body-parser'
configSys = (require './bin/config/configure').getConfig().sys
fse = require 'fs-extra'
os = require 'os'
multer = require 'multer'
_ = require 'underscore'
session = require 'express-session'
RedisStore = require('connect-redis')(session);


# compress = require 'compression'

# libs
compilestyl = require('./bin/libs/compile-stylus-single')

# middlewares
engine= require('./bin/middlewares/hbs-engine')

app = express()

# view engine setup
app.set 'views', path.join(__dirname, 'views')
app.engine 'hbs', engine
app.set 'view engine', 'hbs'


#代理机制
(require './runtime/proxy') app

# app.use compress()
# app.use logger('dev')
app.use bodyParser.urlencoded({limit: '16mb', extended: true})
app.use bodyParser.json({limit: '16mb'})
app.use cookieParser()

#session处理 30分钟超时
app.use session({
    secret: '_customize!!$$123',
    resave: false,
    saveUninitialized: true,
    rolling: true,
    name: 'customize',
    store: new RedisStore({port: 6379}),
    cookie: {
        secure: false,
        httpOnly: false,
        path: '/',
        maxAge: 1800 * 1000
    }
})

#处理文件上传
#Multer will not process any form which is not multipart (multipart/form-data).
app.uploader = multer
  dest: path.resolve os.tmpdir(), "customize"
  limits:
    files: 300
  fileFilter: (req, file, cb) ->
    cb(null, true) # TODO 支持秒传

# 静态资源文件 开发目录和生产目录
if process.env.NODE_ENV is 'production'
  app.use express.static(path.join(__dirname, 'static-dist'))
else
  # 即时编译stylus
  app.use "/sys/css/build.css", compilestyl(src: './stylus/sys/build.styl')
  app.use express.static path.resolve '.', 'static'

#set path
_.each configSys, (value, key) ->
  app.set key, path.join process.env.HOME, value
  fse.ensureDir app.get(key), (err) ->
    console.error "create #{key} failure. \nerr: #{err}" if err




#权限认证
# (require './routes/use-route') app

#轻应用 runtime
(require './runtime/runtime') app

# user routes
# (require './routes/productApp') app
# (require './routes/certificate-upload') app
# (require './routes/certificate') app
# (require './routes/customize') app
# (require './routes/image-upload') app
# (require './routes/generator') app
# (require './routes/user') app
# (require './routes/user-admin') app




# catch 404 and forward to error handler
app.use (req, res, next) ->
  err = new Error('页面找不到')
  err.status = 404
  next(err)


# error handlers

# development error handler
# will print stacktrace
if process.env.NODE_ENV isnt 'production'
  app.use (err, req, res, next) ->
    res.status err.status || 500
    res.render 'error', {
      message: err.message
      error: err
      layout: false
      noLogin: true
    }
else
  # production error handler
  # no stacktraces leaked to user
  app.use (err, req, res, next) ->
    res.status err.status || 500
    res.render 'error', {
      message: ""
      error: {}
      layout: false
      noLogin: true
    }

module.exports = app
